package dao;

import util.Condition;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class CommonDao {
    private static CommonDao commonDao=new CommonDao();
    private CommonDao(){}
    public static CommonDao getInstance(){
        return commonDao;
    }
    public int count(Connection connection,String tableName)throws SQLException{
        String sql="select count(id) as cnt from "+tableName;
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        int counter =0;
        ResultSet resultSet=preparedStatement.executeQuery();
        if(resultSet.next()){
            counter=resultSet.getInt("cnt");
        }
        return counter;
    }

    public int count(Connection connection, String tableName, List<Condition> conditionList)throws SQLException{
        String whereClause=Condition.toWhereClause(conditionList);
        String sql="select count(id) as cnt from "+tableName+" "+whereClause;
        System.out.println("count语句为: "+sql);
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        int counter =0;
        ResultSet resultSet=preparedStatement.executeQuery();
        if(resultSet.next()){
            counter=resultSet.getInt("cnt");
        }
        return counter;
    }

}
